package mydemo.springcloudalibaba.cousumer.order.myLoadBalanced;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 我的负载均衡
 */
@Component
public class MyLb implements MyLoadBanancer {
    // 原子类，分布式计数用
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    /**
     * 自旋锁的方式取得并增加计数
     */
    public final int getAndIcrement(){
        int current;
        int next;
        do{
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("next:" + next);
        return next;
    }

    /**
     * 选择服务
     */
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        if (null == serviceInstances) return null;
        int index = getAndIcrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}





